import json

from django.http import JsonResponse

from Task.models import Task, TaskStatus


def json_response(code, result):
    return JsonResponse({'code': code, 'result': result})


def create_task(request):
    assert request.method == 'POST', '请求方法必须是POST'
    fields = ('title', 'deadline', 'loop', 'running', 'failed')
    body = json.loads(request.body)

    for field in fields:
        assert field in body, f'缺少字段: {field}'

    print(body)

    task = Task(**body)
    task.save()

    return json_response(1, task.serializer())


def cancel_task(request, pk):
    if task := Task.objects.filter(pk=pk).first():
        task.status = TaskStatus.DONE
        task.save()

    return json_response(1, 'OK')


def extend_lifetime(request, pk, lifetime, mode):
    if task := Task.objects.filter(pk=pk).first():
        if mode == 1:
            task.deadline += lifetime
        else:
            task.deadline = lifetime
        task.doing_time = None
        task.save()
    return json_response(1, 'OK')


def test_celery(request):
    print("测试Celery")
    return json_response(1, 'ok')
